package vrann.dataformats.json;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class JsonArray extends JsonElement {	

	private List <JsonElement> values;
	
	public JsonArray()
	{
		values = new ArrayList <JsonElement>();
	}
	
	public JsonArray(String[] vals)
	{
		values = new ArrayList <JsonElement>();
		for (int i = 0; i <  vals.length; i++ ) {
			JsonElement value = new JsonString(vals[i]);
			values.add(value);
		}
	}
	
	public static JsonArray initFromString(String input) throws Exception
	{
		if (input.matches("\\[.*\\]")) {
			JsonArray resultArray = new JsonArray();
			String newInput = input.substring(1, input.length() - 1);		
			String[] arrayValues = newInput.split(",");
			for (int i = 0; i < arrayValues.length; i++) {
				String value = arrayValues[i].trim();
				Character brace = 'N';
				Character rightBrace = 'N';
				if (value.startsWith("[")) {
					brace = '[';
					rightBrace = ']';
				} else if (value.startsWith("{")) {
					brace = '{';
					rightBrace = '}';
				}
				
				if (!brace.equals('N')) {
					int leftBraceCount = countBraceOccurancies(value, brace);
					int rightBraceCount = 0;
					while(rightBraceCount < leftBraceCount) {
						i++;
						leftBraceCount += countBraceOccurancies(arrayValues[i], brace);
						rightBraceCount += countBraceOccurancies(arrayValues[i], rightBrace);
						value += ", " + arrayValues[i];
					}	
				}
				
				value = value.trim();
				
				try {
					JsonElement valueElement = JsonElement.initFromString(value);
					resultArray.put(valueElement);
				} catch (Exception e) {
					throw new Exception("String is not valid JSON Array");
				}
			}
			return resultArray;
		} else {
			throw new Exception("String is not valid JSON Array");
		}
	}
	
	public void put(JsonElement value)
	{
		values.add(value);
	}
	
	public String toString()
	{
		StringBuffer arrayParts = new StringBuffer();
		arrayParts.append("[");
		Iterator<JsonElement> valuesIterator = values.iterator();
		while (valuesIterator.hasNext()) {
			arrayParts.append(valuesIterator.next().getEscapedString());
			if (valuesIterator.hasNext()) {
				arrayParts.append(", ");
			}
		}
		arrayParts.append("]");
		return arrayParts.toString();
	}
	
	public String getEscapedString()
	{
		return toString();
	}
}
